# libs ----
library(sf)
library(geomander)
library(tidyverse)
library(redist)
library(ppmf)
library(grid)
library(patchwork)
library(wacolors)


# helper ----
source('../00_custom_functions.R')

# data ----
state <- "UT"
ppmf19 <- read_ppmf(state, "../../data-raw/ppmf_19.csv")
ppmf12 <- read_ppmf(state, "../../data-raw/ppmf_12.csv")
ppmf4 <- read_ppmf(state, "../../data-raw/ppmf_04.csv")

ppmf19 <- ppmf19 %>% add_geoid() %>% agg() %>% breakdown_geoid()
colnames(ppmf19) <- paste("v19", colnames(ppmf19), sep = "_")
ppmf19 <- ppmf19 %>% rename(GEOID = v19_GEOID)

ppmf12 <- ppmf12 %>% add_geoid() %>% agg() %>% breakdown_geoid()
colnames(ppmf12) <- paste("v12", colnames(ppmf12), sep = "_")
ppmf12 <- ppmf12 %>% rename(GEOID = v12_GEOID)

ppmf4 <- ppmf4 %>% add_geoid() %>% agg() %>% breakdown_geoid()
colnames(ppmf4) <- paste("v4", colnames(ppmf4), sep = "_")
ppmf4 <- ppmf4 %>% rename(GEOID = v4_GEOID)

# comparison ----
census <- create_block_table(state = state)

# all joined ----
block <- census %>%
  left_join(ppmf12, by = 'GEOID') %>%
  left_join(ppmf4, by = 'GEOID') %>% 
  left_join(ppmf19, by = "GEOID")

# and remove duplicates
block <- block %>% select(-contains('.'))

# and set missing block pop/vap to 0
block[is.na(block)] <- 0

# add block_group back (dropped by contains('.'))
block <- block %>% breakdown_geoid()

# from VEST 2018
prec <- st_read('../../data/UT/ut_2018/ut_2018.shp')
prec <- prec %>% st_transform(st_crs(block))

# Get Census Shapes :
sld_low <- tigris::state_legislative_districts('UT', 'lower')
sld_up <- tigris::state_legislative_districts('UT', 'upper')
cd <- tigris::congressional_districts('UT')


# Align ppmf & precincts:
block_prec_match <- geo_match(from = block, to = prec, method = 'centroid')
prec_low_match <- geo_match(from = prec, to = sld_low, method = 'area')
prec_up_match <- geo_match(from = prec, to = sld_up, method = 'area')
prec_cd_match <- geo_match(from = prec, to = cd, method = 'area')

prec <- prec %>% mutate(
  sld_low = sld_low$SLDLST[prec_low_match],
  sld_up = sld_up$SLDUST[prec_up_match],
  cd = cd$CD116FP[prec_cd_match]
)

block$prec <- block_prec_match
ppmf_at_prec <- ppmf_block2prec(block, prec)


# join them together
ut <- prec %>%
  mutate(prec = row_number()) %>%
  left_join(ppmf_at_prec, by = 'prec')

ut$cd <- as.numeric(ut$cd)
ut$sld_low <- as.numeric(ut$sld_low)
ut$sld_up <- as.numeric(ut$sld_up)
ut <- ut %>% mutate(row_id = row_number())
saveRDS(ut, '../../data/UT/ut.Rds', compress = 'xz')
